const db = require('../db/index')
const bcrypt = require('bcryptjs')
// 获取
module.exports.getUserinfo = (req, res) => {
    // const db = require('../db/index')
    const sql = 'select id,username,mickname,email,user_pic from ev_users where id=?'
    db.query(sql, req.user.id, (err, results) => {//身份认证成功后 jwt会帮req挂载user属性保存用户的信息
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('获取失败')
        res.send({
            status: 0,
            msg: '获取用户信息成功',
            data: results[0]
        })
    })
}
// 更新
module.exports.updateUserinfo = (req, res) => {
    const sql = 'update ev_users set ? where id=?'
    db.query(sql, [req.body, req.body.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('更新用户信息失败')
        return res.cc('修改成功!', 0)
    })
}
// 密码
module.exports.updatePassword = (req, res) => {
    const sql = 'select * from ev_users where id=?'
    db.query(sql, req.user.id, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('未查找到用户')
        const compareResult = bcrypt.compareSync(req.body.oldPwd, results[0].password)
        if (!compareResult) return res.cc('旧密码错误')
        const sqlpwd = 'update ev_users set password=? where id=? '
        const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
        db.query(sqlpwd, [newPwd, req.user.id], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('重置密码失败')
            res.cc('重置密码成功', 0)
        })
    })
}
// 头像
module.exports.updateAvatar = (req, res) => {
    const sql = 'update ev_users set user_pic=? where id=?'
    db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('修改头像失败')
        res.cc('修改头像成功', 0)
    })
}